﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;

namespace Framework.Common.Serializer
{
    public abstract class SerializeBase<To>
    {
        public abstract To Serialize(object obj);
        public abstract bool SerializeToFile(object obj, string fullPath);
        public abstract T DeSerialize<T>(To source);
        public abstract T DeSerializeFromFile<T>(string fullPath);

        protected bool SerializeToFile(object obj, string fullPath, Action<FileStream> serialize)
        {
            try
            {
                using (FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    serialize(fs);
                    return true;
                }
            }
            catch (SerializationException e)
            {
                LogHelper.Error("序列化出错", e);
                return false;
            }
        }

        protected T DeSerializeFromFile<T>(string fullPath, Func<FileStream, object> deserialize)
        {
            try
            {
                using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    object obj = deserialize(fs); // formatter.Deserialize(fs);
                    return (T)obj;
                }
            }
            catch (SerializationException e)
            {
                LogHelper.Error("反序列化出错", e);
                return default(T);
            }
        }
    }
}
